unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, GR32_Image,GR32, GR32_Layers,ExtCtrls,FileCtrl,GR32_FloatMap,
  ComCtrls, Menus, XPMan, ExtDlgs, StdCtrls, Buttons, ToolWin, ImgList,
  Spin, Math, gmCrop,GR32_RangeBars,Grids ,ShellApi,GR32_OrdinalMaps,ImageTrainer;

type
  TFrm_Main = class(TForm)
    sb: TStatusBar;
    MainMenu1: TMainMenu;
    File1: TMenuItem;
    XPManifest1: TXPManifest;
    Open1: TMenuItem;
    ImageList1: TImageList;
    ColorDialog: TColorDialog;
    ImgView: TImgView32;
    Panel4: TPanel;
    TrackBarProgress: TTrackBar;
    ControlBar1: TControlBar;
    ToolBar1: TToolBar;
    ToolButton1: TToolButton;
    ToolButton2: TToolButton;
    ToolButton3: TToolButton;
    ToolButton4: TToolButton;
    btnCommit: TToolButton;
    ToolButton6: TToolButton;
    ComboBox1: TComboBox;
    SaveDialog1: TSaveDialog;
    N1: TMenuItem;
    Save1: TMenuItem;
    Exit1: TMenuItem;
    ToolBar2: TToolBar;
    ScaleCombo: TComboBox;
    ComboFileFormat: TComboBox;
    ToolButton7: TToolButton;
    ggbrShieldOpacity: TGaugeBar;
    shpShieldColor: TShape;
    pb: TProgressBar;
    Process1: TMenuItem;
    raining1: TMenuItem;
    Recognizing1: TMenuItem;
    N2: TMenuItem;
    NeuralOption1: TMenuItem;
    Timer1: TTimer;
    Load1: TMenuItem;
    OpenDialog1: TOpenDialog;
    procedure FormCreate(Sender: TObject);
    procedure ImgViewPaintStage(Sender: TObject; Buffer: TBitmap32;
      StageNum: Cardinal);
    procedure Open1Click(Sender: TObject);
    procedure ImgViewMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
    procedure ImgViewMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer; Layer: TCustomLayer);
    procedure ImgViewMouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
    procedure sbDrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel;
      const Rect: TRect);
    procedure FormDestroy(Sender: TObject);
    procedure TrackBarProgressChange(Sender: TObject);
    procedure ToolButton3Click(Sender: TObject);
    procedure ToolButton2Click(Sender: TObject);
    procedure ToolButton4Click(Sender: TObject);
    procedure ToolButton1Click(Sender: TObject);
    procedure ggbrShieldOpacityChange(Sender: TObject);
    procedure shpShieldColorMouseDown(Sender: TObject;
      Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
    procedure ImgViewResize(Sender: TObject);
    procedure View1Click(Sender: TObject);
    procedure btnCommitClick(Sender: TObject);
    procedure ComboBox1Change(Sender: TObject);
    procedure Save1Click(Sender: TObject);
    procedure ScaleComboChange(Sender: TObject);
    procedure ComboFileFormatClick(Sender: TObject);
    procedure Exit1Click(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
    procedure Recognizing1Click(Sender: TObject);
    procedure raining1Click(Sender: TObject);
    procedure Load1Click(Sender: TObject);


  private
    { Private declarations }
    FBackLayer         : TBitmapLayer;
    FRBLayer           : TRubberBandLayer;
    FCrop              : TgmCrop;
    FDrawing           : Boolean;
    FStartPoint        : TPoint; // control coordinate space
    FEndPoint          : TPoint; // control coordinate space
    FRBLayerTopLeft    : TPoint; // bitmap coordinate space
    FRBLayerBottomRight: TPoint; // bitmap coordinate space
    DirectoryUpdateInProgress:  BOOLEAN;
    FileList                 :  TStringList;
    data_targets: TStringList;
    data_inputs : TStringList;
    PROCEDURE UpdateFileList;
    PROCEDURE DisplayCurrentImage;
    procedure RBResizing(Sender: TObject; const OldLocation: TFloatRect;
      var NewLocation: TFloatRect; DragState: TDragState; Shift: TShiftState);
    procedure RBMouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure LoadIniFile;
    {procedure AddRowToGrid(Grid: TStringGrid; data: array of string); }
    procedure InitValue;
  public
    { Public declarations }
  end;

var
  Frm_Main: TFrm_Main;
  FDirectory: String;
  combo_index: integer;
  Train          : TImageTraner;
  starttime: integer;
  start: integer;
  recon : boolean;
CONST
  KeywordSetup     = 'Setup';
  KeywordDirectory = 'Directory';

implementation

uses
    gmIO ,
    IniFiles,
    gmImageProcessFuncs,
    blob ;

{$R *.dfm}
FUNCTION Plural(CONST n:  Integer; CONST singularform,pluralform:  STRING):  STRING;
BEGIN  {function similar to one on p. 314, Byte, December 1988}
    IF   n = 1
    THEN RESULT := singularform
    ELSE
      IF   pluralform = ''
      THEN RESULT := singularform + 's'
      ELSE RESULT := pluralform
END {Plural};
procedure TFrm_Main.LoadIniFile;
var
  directory : String;
  IniFile:  TIniFile;
begin
  DirectoryUpdateInProgress := TRUE;
  IniFile := TIniFile.Create(ChangeFileExt(ParamStr(0), '.INI'));
 try
   directory := IniFile.ReadString(KeywordSetup, KeyWordDirectory,
                    ExtractFilePath(ParamStr(0)));

    if DirectoryExists(directory) then
    begin
     FDirectory:= directory;
     sb.Panels[3].Text:= directory;
    end
 finally
   IniFile.Free;
 end;

end;
procedure TFrm_Main.FormCreate(Sender: TObject);
var
  ProgressBarStyle: integer;

begin
{$IFDEF GIF}
  // Allow GIF images to be seen
  RadioGroupFileFormat.Items.Add('GIF');
{$ENDIF}
  Train := TImageTraner.Create;
  recon := false;
 //enable status bar 2nd Panel custom drawing
  sb.Panels[2].Style := psOwnerDraw;

  //place the progress bar into the status bar
  pb.Parent := sb;

  //remove progress bar border
  ProgressBarStyle := GetWindowLong(sb.Handle,
                                    GWL_EXSTYLE);
  ProgressBarStyle := ProgressBarStyle
                      - WS_EX_STATICEDGE;
  SetWindowLong(pb.Handle,
                GWL_EXSTYLE,
                ProgressBarStyle);
 LoadIniFile;
 with ImgView.PaintStages[0]^ do
  begin
    if Stage = PST_CLEAR_BACKGND then Stage := PST_CUSTOM;
  end;

  ImgView.RepaintMode := rmOptimizer;

 start := 0;
 DirectoryUpdateInProgress := FALSE;
 FileList := TStringList.Create;
 FCrop               := nil;
 FRBLayer            := nil;
 FDrawing            := False;
 FStartPoint         := Point(0, 0);
 FEndPoint           := Point(0, 0);
 FRBLayerTopLeft     := Point(0, 0);
 FRBLayerBottomRight := Point(0, 0);

 FBackLayer        := TBitmapLayer.Create(ImgView.Layers);
 FBackLayer.Scaled := True;

 ImgView.Bitmap.DrawMode := dmBlend;
 Recognizing1.Enabled:= false;
 raining1.Enabled:=False;
 data_targets:= TStringList.Create;
 data_inputs := TStringList.Create;
end;

procedure TFrm_Main.ImgViewPaintStage(Sender: TObject; Buffer: TBitmap32;
  StageNum: Cardinal);
const            //0..1
  Colors: array [Boolean] of TColor32 = ($FFFFFFFF, $FFB0B0B0);
var
  R: TRect;
  I, J: Integer;
  OddY: Integer;
  TilesHorz, TilesVert: Integer;
  TileX, TileY: Integer;
  TileHeight, TileWidth: Integer;
begin
  TileHeight := 13;
  TileWidth := 13;

  TilesHorz := Buffer.Width div TileWidth;
  TilesVert := Buffer.Height div TileHeight;
  TileY := 0;

  for J := 0 to TilesVert do
  begin
    TileX := 0;
    OddY := J and $1;
    for I := 0 to TilesHorz do
    begin
      R.Left := TileX;
      R.Top := TileY;
      R.Right := TileX + TileWidth;
      R.Bottom := TileY + TileHeight;
      Buffer.FillRectS(R, Colors[I and $1 = OddY]);
      Inc(TileX, TileWidth);
    end;
    Inc(TileY, TileHeight);
  end;
end;



procedure TFrm_Main.Open1Click(Sender: TObject);
var
  Filename:  STRING;
  Dir: String;
begin
  IF   NOT DirectoryUpdateInProgress
  THEN BEGIN
    // Update INI file for next time
    SelectDirectory('Select Directory','',Dir);
    FDirectory:=Dir;
    WritePrivateProfileString(NIL, NIL, NIL, pChar(Filename));
  END;
end;
PROCEDURE TFrm_Main.RBResizing(Sender: TObject; const OldLocation: TFloatRect;
      var NewLocation: TFloatRect; DragState: TDragState; Shift: TShiftState);
VAR
  tl, br: TPoint;
begin
  if Assigned(FCrop) then
  begin
    tl.X := Round(FRBLayer.Location.Left);
    tl.Y := Round(FRBLayer.Location.Top);
    br.X := Round(FRBLayer.Location.Right);
    br.Y := Round(FRBLayer.Location.Bottom);

    FCrop.FCropStart := ImgView.ControlToBitmap(tl);
    FCrop.FCropEnd   := ImgView.ControlToBitmap(br);
    FCrop.DrawShield;
  end;
END;


PROCEDURE TFrm_Main.RBMouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
VAR
  tl, br: TPoint;
BEGIN
  if Assigned(FCrop) then
  begin
    tl.X := Round(FRBLayer.Location.Left);
    tl.Y := Round(FRBLayer.Location.Top);
    br.X := Round(FRBLayer.Location.Right);
    br.Y := Round(FRBLayer.Location.Bottom);

    FCrop.FCropStart := ImgView.ControlToBitmap(tl);
    FCrop.FCropEnd   := ImgView.ControlToBitmap(br);
    FCrop.DrawShield;

    FRBLayerTopLeft     := FCrop.FCropStart;
    FRBLayerBottomRight := FCrop.FCropEnd;
  end;
END;
procedure TFrm_Main.ImgViewMouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
begin
 if not Assigned(FCrop) then
  begin
    FStartPoint := Point(X, Y);
    FEndPoint   := Point(X, Y);

    ImgView.Canvas.Pen.Mode    := pmNotXor;
    ImgView.Canvas.Pen.Style   := psDot;
    ImgView.Canvas.Brush.Style := bsClear;
    ImgView.Canvas.Rectangle(FStartPoint.X, FStartPoint.Y, FEndPoint.X, FEndPoint.Y);

    FDrawing := True;
  end;
end;

procedure TFrm_Main.ImgViewMouseMove(Sender: TObject; Shift: TShiftState; X,
  Y: Integer; Layer: TCustomLayer);
begin
   if FDrawing then
  begin
    // erasing the last figure
    ImgView.Canvas.Rectangle(FStartPoint.X, FStartPoint.Y, FEndPoint.X, FEndPoint.Y);
    FEndPoint := Point(X, Y);
    ImgView.Canvas.Rectangle(FStartPoint.X, FStartPoint.Y, FEndPoint.X, FEndPoint.Y);
  end;

end;

procedure TFrm_Main.ImgViewMouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
var
  tl, br: TPoint;

begin
 if FDrawing then
  begin
    FDrawing := False;

    tl.X := MinIntValue([FStartPoint.X, FEndPoint.X]);
    tl.Y := MinIntValue([FStartPoint.Y, FEndPoint.Y]);
    br.X := MaxIntValue([FStartPoint.X, FEndPoint.X]);
    br.Y := MaxIntValue([FStartPoint.Y, FEndPoint.Y]);

    FCrop := TgmCrop.Create(FBackLayer.Bitmap.Width, FBackLayer.Bitmap.Height,
                            ImgView.Layers, FBackLayer.Location);

    FCrop.ShieldOpacity := 40;
    FCrop.FCropStart    := ImgView.ControlToBitmap(tl);
    FCrop.FCropEnd      := ImgView.ControlToBitmap(br);

    FCrop.DrawShield;

    if Assigned(FRBLayer) then
    begin
      FreeAndNil(FRBLayer);
    end;

    FRBLayer            := TRubberBandLayer.Create(ImgView.Layers);
    FRBLayer.Location   := FloatRect(tl.X, tl.Y, br.X, br.Y);
    FRBLayer.OnResizing := RBResizing;
    FRBLayer.OnMouseUp  := RBMouseUp;


    ggbrShieldOpacity.Position := FCrop.ShieldOpacity;
    //lblShieldOpacity.Caption   := 'Shield Opacity: ' + IntToStr(ggbrShieldOpacity.Position) + '%';
    shpShieldColor.Brush.Color := FCrop.ShieldWinColor;

    FRBLayerTopLeft     := FCrop.FCropStart;
    FRBLayerBottomRight := FCrop.FCropEnd;
    ggbrShieldOpacity.Enabled:=True;
    shpShieldColor.Enabled:=True;
  end;


end;
procedure TFrm_Main.sbDrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel;
  const Rect: TRect);
begin
 if Panel = sb.Panels[2] then
  with pb do begin
    Top := Rect.Top;
    Left := Rect.Left;
    Width := Rect.Right - Rect.Left - 15;
    Height := Rect.Bottom - Rect.Top;
  end
end;
PROCEDURE TFrm_Main.DisplayCurrentImage;
 VAR
  Bmp    : TBitmap32;
  ARect  : TRect;
  TopLeft: TPoint;
begin

    bmp := LoadGraphicsFile( FileList.Strings[TrackBarProgress.Position] );
    if not Assigned(Bmp) then
    begin
      MessageDlg('Cannot load picture ''' + ExtractFileName(FileList.Strings[TrackBarProgress.Position]) + '''', mtError, [mbOK], 0);
      Exit;
    end;
     try
        FBackLayer.Bitmap.Assign(Bmp);
        FBackLayer.Bitmap.DrawMode := dmBlend;

        ImgView.Bitmap.Width  := Bmp.Width;
        ImgView.Bitmap.Height := Bmp.Height;
        ImgView.Bitmap.Clear($FFFF0000);

        ARect := ImgView.GetBitmapRect;

        TopLeft := ImgView.ControlToBitmap( Point(ARect.Left, ARect.Top) );

        FBackLayer.Location := FloatRect(TopLeft.X, TopLeft.Y,
                                       ImgView.Bitmap.Width,
                                       ImgView.Bitmap.Height);
      if Assigned(FRBLayer) then
      begin
        FreeAndNil(FRBLayer);
      end;

      if Assigned(FCrop) then
      begin
        FreeAndNil(FCrop);
      end;
    finally
      Bmp.Free;
    end ;
    sb.Panels[0].Text :=
       'Image ' +
       IntToStr(1 + TrackBarProgress.Position) +
       ':  ' +
       ExtractFilename( FileList.Strings[TrackBarProgress.Position] )+
       '   [' +
       IntToStr(FBackLayer.Bitmap.Width) + 'x' +
       IntToStr(FBackLayer.Bitmap.Height) + ' pixels]';

end;

// For now, only look for single type of file in directory for inclusion in list
PROCEDURE TFrm_Main.UpdateFileList;
  CONST
    Sentinel   = '|';
  VAR
    FileSpec   :  STRING;
    i          :  INTEGER;
    Index      :  INTEGER;
    Line       :  STRING;
    Path       :  STRING;
    ReturnCode :  Cardinal;
    SearchRec  :  TSearchRec;
    SortKey    :  STRING;
    StepSize   :  INTEGER;
    StringList :  TStringList;
BEGIN
  Screen.Cursor := crHourGlass;
  TRY
    FileList.Clear;
    Path     := FDirectory;
    FileSpec := '*.' + ComboFileFormat.Items[ComboFileFormat.ItemIndex];

    IF   Path[LENGTH(Path)] <> '\'
    THEN Path := Path + '\';           // Just in case

    StringList := TStringList.Create;
    TRY
      // Assume filenames are numbers that should be in order
      StringList.Sorted := TRUE;

      // To find all directories, including ones that may have the "system"
      // attribute, just ask for all files, faAnyFile, here.
      ReturnCode := SysUtils.FindFirst(Path + Filespec, faAnyFile, SearchRec);
      WHILE ReturnCode = 0 DO
      BEGIN
        IF   (SearchRec.Attr AND faDirectory <> faDirectory) AND
             (SearchRec.Name <> '.')                         AND
             (SearchRec.Name <> '..')   // exclude '.' and '..' directories
        THEN BEGIN
          Line := Path + SearchRec.Name;
          SortKey := SearchRec.Name;
          SortKey := Format('%20s', [Sortkey]);
          StringList.Add(SortKey + Sentinel + Line)
        END;
        ReturnCode := SysUtils.FindNext(SearchRec)
      END;
      SysUtils.FindClose(SearchRec);

      // Now load sorted StringList into FileList
      FOR i := 0 TO StringList.Count-1 DO
      BEGIN
        Line := StringList.Strings[i];
        Index := POS(Sentinel, Line);
        FileList.Add(COPY(Line,Index+1, LENGTH(Line)-Index))
      END;

    FINALLY
      StringList.Clear;
      StringList.Free
    END;

    sb.Panels[1].Text := InttoStr(FileList.Count) + ' ' +
         ComboFileFormat.Items[ComboFileFormat.ItemIndex] +
         Plural(FileList.Count, ' file', '');
    TrackBarProgress.Position := 0;

    IF   FileList.Count > 0
    THEN  BEGIN
       TrackBarProgress.Max := FileList.Count-1;
       raining1.Enabled:= True;
    END;
    // Heuristic to avoid solid black lines of tick marks when many images
    // present
    StepSize := FileList.Count DIV 50;
    IF   StepSize = 0
    THEN StepSize := 1;
    TrackBarProgress.Frequency := StepSize;

    IF   FileList.Count = 0
    THEN BEGIN
      ImgView.Bitmap := NIL;

    END
    ELSE DisplayCurrentImage;

    TrackBarProgress.Visible := (FileList.Count > 1);

    // Make sure Print button available when only single image
  //  PanelPlay.Visible        := (FileList.Count > 0)
  FINALLY
    Screen.Cursor := crDefault
  END
END {UpdateFileList};

procedure TFrm_Main.FormDestroy(Sender: TObject);
begin
  FileList.Clear;
  FileList.Free;
  FRBLayer.Free;
  FCrop.Free;
  FBackLayer.Free;
  Train.Destroy;
  data_targets.Free;
  data_inputs.Free;
end;

procedure TFrm_Main.TrackBarProgressChange(Sender: TObject);
begin
   DisplayCurrentImage;
end;
procedure TFrm_Main.InitValue;
var
 filename : string;
begin
 inc(start);
 //setlength(inputs,2);
 filename:=Format(GetCurrentDir+'\image\%d.bmp',[start]);
 data_inputs.Add(filename);
 data_targets.Add(IntToStr(ComboBox1.ItemIndex));
 if not recon then
    FBackLayer.Bitmap.SaveToFile(filename);
end;


procedure TFrm_Main.ToolButton3Click(Sender: TObject);
var
 Index : Integer;
begin
   Index := TrackBarProgress.Position + 1;
   IF   (Index < 0) OR (Index > FileList.Count - 1)
   THEN TrackBarProgress.Position:=0
   ELSE TrackBarProgress.Position := Index;
end;

procedure TFrm_Main.ToolButton2Click(Sender: TObject);
var
 Index : Integer;
begin
   Index := TrackBarProgress.Position - 1;
   IF   (Index < 0) OR (Index > FileList.Count - 1)
   THEN TrackBarProgress.Position:=0
   ELSE TrackBarProgress.Position := Index;
end;
procedure TFrm_Main.ToolButton4Click(Sender: TObject);
begin
  TrackBarProgress.Position := FileList.Count-1;
  DisplayCurrentImage
end;

procedure TFrm_Main.ToolButton1Click(Sender: TObject);
begin
  TrackBarProgress.Position := 0;
  DisplayCurrentImage
end;

procedure TFrm_Main.ggbrShieldOpacityChange(Sender: TObject);
begin
  //lblShieldOpacity.Caption := 'Shield Opacity: ' + IntToStr(ggbrShieldOpacity.Position) + '%';
  FCrop.ShieldOpacity      := ggbrShieldOpacity.Position;
  FCrop.DrawShield;

end;

procedure TFrm_Main.shpShieldColorMouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  ColorDialog.Color := FCrop.ShieldWinColor;
  if ColorDialog.Execute then
  begin
    FCrop.ShieldColor32 := Color32(ColorDialog.Color);
    FCrop.DrawShield;
  end;
end;

procedure TFrm_Main.ImgViewResize(Sender: TObject);
var
 tl, br: TPoint;
begin
  if Assigned(FRBLayer) then
  begin
    tl := ImgView.BitmapToControl(FRBLayerTopLeft);
    br := ImgView.BitmapToControl(FRBLayerBottomRight);

    FRBLayer.Location := FloatRect(tl.X, tl.Y, br.X, br.Y);
  end;
end;
procedure TFrm_Main.View1Click(Sender: TObject);
begin
  if (Sender is TMenuItem) then
    TMenuItem(sender).Checked:= not (sender as TMenuItem).Checked;
end;

procedure TFrm_Main.btnCommitClick(Sender: TObject);
var
  CropRect, ARect: TRect;
  CropBitmap     : TBitmap32;
  TopLeft        : TPoint;

begin
   if Assigned(FCrop) then
  begin
    Screen.Cursor := crHourGlass;
    try
      // doing crop...
      ImgView.Bitmap.SetSize(FCrop.CropAreaWidth, FCrop.CropAreaHeight);

      CropBitmap := TBitmap32.Create;

      try
        CropBitmap.DrawMode := dmBlend;
        CropRect := Rect(FCrop.FCropStart.X, FCrop.FCropStart.Y, FCrop.FCropEnd.X, FCrop.FCropEnd.Y);
        CopyRect32WithARGB(CropBitmap, FBackLayer.Bitmap, CropRect, $00FFFFFF);
        FBackLayer.Bitmap.SetSize(CropBitmap.Width, CropBitmap.Height);
        CopyBitmap32(FBackLayer.Bitmap, CropBitmap);

        // get location of the bitmap in the TImgView32
        ARect := ImgView.GetBitmapRect;

        { Convert the top-left point of the background bitmap of the TImage32
          from control coordinate to bitmap coordinate. }
        TopLeft := ImgView.ControlToBitmap( Point(ARect.Left, ARect.Top) );

        FBackLayer.Location := FloatRect(TopLeft.X, TopLeft.Y,
                                         ImgView.Bitmap.Width,
                                         ImgView.Bitmap.Height);
        ggbrShieldOpacity.Enabled:=False;
        shpShieldColor.Enabled:=False;

      finally
        CropBitmap.Free;
      end;
      if Assigned(FRBLayer) then
      begin
        FreeAndNil(FRBLayer);
      end;
      FreeAndNil(FCrop);
    finally
      Screen.Cursor := crDefault;
    end;
  end;
  InitValue;

end;
{
procedure TFrm_Main.AddRowToGrid(Grid: TStringGrid; data: array of string);
var
 i: integer;
 FirstRowIsEmpty: boolean;
begin
 FirstRowIsEmpty := true;
 for i := Grid.FixedCols to Grid.ColCount - 1 do
   if Grid.Cells[i, Grid.FixedRows] <> '' then begin
      FirstRowIsEmpty := false;
      break;
   end;
  if not FirstRowIsEmpty then
   Grid.RowCount := Grid.RowCount + 1;
   Grid.ColCount := length(data);
 // copy the data to the last row
 for i := 0 to length(data) do begin
   if i > High(Data) then
     Grid.Cells[Grid.FixedCols + i, Grid.RowCount - 1] := ''
   else
     Grid.Cells[Grid.FixedCols + i, Grid.RowCount - 1] := Data[i];
 end;
end;
}
procedure TFrm_Main.ComboBox1Change(Sender: TObject);
begin
  combo_index := ComboBox1.ItemIndex;
end;

procedure TFrm_Main.Save1Click(Sender: TObject);
begin
  if SaveDialog1.Execute then
    Train.SaveNN(SaveDialog1.FileName);
end;

procedure TFrm_Main.ScaleComboChange(Sender: TObject);
var
  S: string;
  I: Integer;
begin
  S := ScaleCombo.Text;
  S := StringReplace(S, '%', '', [rfReplaceAll]);
  S := StringReplace(S, ' ', '', [rfReplaceAll]);
  if S = '' then Exit;
  I := StrToIntDef(S, -1);
  if (I < 1) or (I > 2000) then I := Round(ImgView.Scale * 100)
  else ImgView.Scale := I / 100;
  ScaleCombo.Text := IntToStr(I) + '%';
  ScaleCombo.SelStart := Length(ScaleCombo.Text) - 1;
end;

procedure TFrm_Main.ComboFileFormatClick(Sender: TObject);
begin
  LoadIniFile;
  UpdateFileList;
  ImgView.Bitmap.Clear;
  if FileList.Count <> 0 then
    ComboFileFormat.Enabled:=False
  else
    ComboFileFormat.Enabled:=True;
end;

procedure TFrm_Main.Exit1Click(Sender: TObject);
begin
  close;
end;

procedure TFrm_Main.Timer1Timer(Sender: TObject);
var
 i: integer;
 error : double;
begin
  inc(starttime);
  error := 0;
  for i := 0 to data_inputs.Count -1 do
     error :=Train.Learn(data_inputs[i], data_targets[i]);

  sb.Panels[4].Text:= 'MSE : '+ FloatToStr(error);
  pb.Position:= starttime;

  if (starttime > 5000)  then
    Timer1.Enabled := false ;
end;

procedure TFrm_Main.Recognizing1Click(Sender: TObject);
var
 map: TBitmap32;
 canvas : TCanvas ;

begin
 map := TBitmap32.Create;
 map.SetSizeFrom(FBackLayer.Bitmap);
 try
   //bmp.Assign(FBackLayer.Bitmap);
   Train.Guess(FBackLayer.Bitmap,map);
  // Blob_detection(map, Data_Points );
  // Blob_tracking(Data_Points,Finger, FBackLayer.Bitmap.Canvas,
  //                 20, 10, 200, true, false );
   FBackLayer.Bitmap.Assign(map);
 finally
   map.Free;
 end;

end;

procedure TFrm_Main.raining1Click(Sender: TObject);
begin
   pb.Min := 0;
   starttime:= 0;
   pb.Max := 5000;
   pb.Position := 0;
   Timer1.Enabled := true;
   raining1.Enabled:= False;
   Recognizing1.Enabled:= True;
   recon:=True;
end;

procedure TFrm_Main.Load1Click(Sender: TObject);
begin
 if OpenDialog1.Execute then
       Train.LoadNN(OpenDialog1.FileName);
 recon:= True;
 Recognizing1.Enabled:= True;
end;

end.
